package com.example.demo.controller;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import com.example.demo.dto.NewTaskDTO;
import com.example.demo.dto.DataSourceTaskStatsDTO;
import com.example.demo.dto.TaskDetailDTO;
import com.example.demo.dto.DataSourceSearchConfigDTO;
import com.example.demo.dto.PageExtra;
import com.example.demo.request.SearchNewTaskRequest;
import com.example.demo.request.CreateNewTaskRequest;
import com.example.demo.response.ApiResponse;
import com.example.demo.service.NewTaskService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/new-tasks")
public class NewTaskController {

    @Autowired
    private NewTaskService newTaskService;


    @GetMapping
    public ResponseEntity<ApiResponse<List<NewTaskDTO>>> getNewTasks(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long dataSourceId,
            @RequestParam(required = false) Integer isAssigned,
            HttpServletRequest request) {
        List<NewTaskDTO> newTasks = newTaskService.getNewTasks(page, size, dataSourceId, isAssigned);
        long total = newTaskService.countNewTasks(dataSourceId, isAssigned);
        PageExtra pageExtra = new PageExtra(page, size, total);
        
        return ResponseEntity.ok(
                ApiResponse.success(newTasks, "查询成功", request.getRequestURI(), pageExtra)
        );
    }


    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<NewTaskDTO>> getNewTaskById(
            @PathVariable Long id,
            HttpServletRequest request) {
        NewTaskDTO newTaskDTO = newTaskService.getNewTaskById(id);
        return ResponseEntity.ok(
                ApiResponse.success(newTaskDTO, "查询成功", request.getRequestURI(), null)
        );
    }


    @GetMapping("/biz/{bizUniqueId}")
    public ResponseEntity<ApiResponse<NewTaskDTO>> getNewTaskByBizUniqueId(
            @PathVariable String bizUniqueId,
            HttpServletRequest request) {
        NewTaskDTO newTaskDTO = newTaskService.getNewTaskByBizUniqueId(bizUniqueId);
        return ResponseEntity.ok(
                ApiResponse.success(newTaskDTO, "查询成功", request.getRequestURI(), null)
        );
    }


    @PostMapping
    public ResponseEntity<ApiResponse<NewTaskDTO>> createNewTask(
            @Valid @RequestBody CreateNewTaskRequest request,
            HttpServletRequest httpRequest) {
        NewTaskDTO newTaskDTO = newTaskService.createNewTask(request);
        return ResponseEntity.ok(
                ApiResponse.created(newTaskDTO, "创建成功", httpRequest.getRequestURI())
        );
    }


    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<NewTaskDTO>> updateNewTask(
            @PathVariable Long id,
            @Valid @RequestBody CreateNewTaskRequest request,
            HttpServletRequest httpRequest) {
        NewTaskDTO newTaskDTO = newTaskService.updateNewTask(id, request);
        return ResponseEntity.ok(
                ApiResponse.success(newTaskDTO, "更新成功", httpRequest.getRequestURI(), null)
        );
    }


    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteNewTask(
            @PathVariable Long id,
            HttpServletRequest request) {
        newTaskService.deleteNewTask(id);
        return ResponseEntity.ok(
                ApiResponse.success(null, "删除成功", request.getRequestURI(), null)
        );
    }


    @PutMapping("/{id}/assigned-status")
    public ResponseEntity<ApiResponse<Void>> updateNewTaskAssignedStatus(
            @PathVariable Long id,
            @RequestParam Integer isAssigned,
            HttpServletRequest request) {
        newTaskService.updateNewTaskAssignedStatus(id, isAssigned);
        return ResponseEntity.ok(
                ApiResponse.success(null, "更新成功", request.getRequestURI(), null)
        );
    }


    @PutMapping("/{id}/complete-status")
    public ResponseEntity<ApiResponse<Void>> updateNewTaskCompleteStatus(
            @PathVariable Long id,
            @RequestParam Integer isComplete,
            HttpServletRequest request) {
        newTaskService.updateNewTaskCompleteStatus(id, isComplete);
        return ResponseEntity.ok(
                ApiResponse.success(null, "更新成功", request.getRequestURI(), null)
        );
    }


    @PostMapping("/sync-from-datasource/{dataSourceId}")
    public ResponseEntity<ApiResponse<Integer>> syncTasksFromDataSource(
            @PathVariable Long dataSourceId,
            HttpServletRequest request) {
        int syncedCount = newTaskService.syncTasksFromDataSource(dataSourceId);
        return ResponseEntity.ok(
                ApiResponse.success(syncedCount, "同步成功，共同步" + syncedCount + "条任务", request.getRequestURI(), null)
        );
    }


    @GetMapping("/overview/stats")
    public ResponseEntity<ApiResponse<List<DataSourceTaskStatsDTO>>> getTaskOverviewStats(
            HttpServletRequest request) {
        List<DataSourceTaskStatsDTO> statsList = newTaskService.getAllDataSourceTaskStats();
        return ResponseEntity.ok(
                ApiResponse.success(statsList, "获取统计信息成功", request.getRequestURI(), null)
        );
    }


    @GetMapping("/overview/stats/{dataSourceId}")
    public ResponseEntity<ApiResponse<DataSourceTaskStatsDTO>> getDataSourceTaskStats(
            @PathVariable Long dataSourceId,
            HttpServletRequest request) {
        DataSourceTaskStatsDTO stats = newTaskService.getDataSourceTaskStatsById(dataSourceId);
        return ResponseEntity.ok(
                ApiResponse.success(stats, "获取统计信息成功", request.getRequestURI(), null)
        );
    }

   
    @GetMapping("/overview/details/{dataSourceId}")
    public ResponseEntity<ApiResponse<List<TaskDetailDTO>>> getDataSourceTaskDetails(
            @PathVariable Long dataSourceId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) Integer isAssigned,
            HttpServletRequest request) {
        List<TaskDetailDTO> taskDetails = newTaskService.getTaskDetails(page, size, dataSourceId, isAssigned);
        long total = newTaskService.countNewTasks(dataSourceId, isAssigned);
        PageExtra pageExtra = new PageExtra(page, size, total);
        
        return ResponseEntity.ok(
                ApiResponse.success(taskDetails, "获取任务详情成功", request.getRequestURI(), pageExtra)
        );
    }


    @GetMapping("/detail/{id}")
    public ResponseEntity<ApiResponse<TaskDetailDTO>> getTaskDetail(
        @PathVariable Long id,
            HttpServletRequest request) {
        TaskDetailDTO taskDetail = newTaskService.getTaskDetail(id);
        return ResponseEntity.ok(
                ApiResponse.success(taskDetail, "获取任务详细信息成功", request.getRequestURI(), null)
        );
    }


    @GetMapping("/search-config/{dataSourceId}")
    public ResponseEntity<ApiResponse<DataSourceSearchConfigDTO>> getDataSourceSearchConfig(
            @PathVariable Long dataSourceId,
            HttpServletRequest request) {
        DataSourceSearchConfigDTO config = newTaskService.getDataSourceSearchConfig(dataSourceId);
        return ResponseEntity.ok(
                ApiResponse.success(config, "获取搜索配置成功", request.getRequestURI(), null)
        );
    }
    

    @PostMapping("/search")
    public ResponseEntity<ApiResponse<List<TaskDetailDTO>>> searchNewTasks(
            @Valid @RequestBody SearchNewTaskRequest searchRequest,
            HttpServletRequest request) {
        List<TaskDetailDTO> tasks = newTaskService.searchNewTasks(searchRequest);
        long total = newTaskService.countSearchNewTasks(searchRequest);
        PageExtra pageExtra = new PageExtra(searchRequest.getPage(), searchRequest.getSize(), total);
        
        return ResponseEntity.ok(
                ApiResponse.success(tasks, "搜索成功", request.getRequestURI(), pageExtra)
        );
    }
}